package graph.weighted;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
/**
 * 
 * @Title: AdjacentList.java 
 * @Package graph 
 * @Description: 图论算法的基础类：底层基于TreeMap的邻接表
 *                  基于无向无权图修改为无向带权图
 * @author CandyWall   
 * @date 2021年1月14日 下午12:35:12 
 * @version V1.0
 */
public class CandyWeightedGraph implements Cloneable, Serializable {
    private int vertex_num; // 当前图中的顶点数
    private int edge_num;   // 当前图中的边数
    private TreeMap<Integer, Integer>[] adj;    // 邻接矩阵
    private boolean directed; // 是否是有向图
    
    // 是否是有向图
    public boolean isDirected() {
        return directed;
    }

    /**
     * 从文件中加载一个图
     * @param filename
     */
    public CandyWeightedGraph(String filename, boolean directed) {
        this.directed = directed;
        try(Scanner scanner = new Scanner(new File(filename))) {
            // 读取顶点数
            vertex_num = scanner.nextInt();
            if(vertex_num < 0) {
                throw new IllegalArgumentException("顶点数必须是非负数！");
            }
            
            this.edge_num = 0;
            // 读取边数
            int e = scanner.nextInt();
            if(e < 0) {
                throw new IllegalArgumentException("边数必须是非负数！");
            }
            // 初始化邻接表
            adj = new TreeMap[vertex_num];
            for(int i = 0; i < vertex_num; i++) {
                adj[i] = new TreeMap<>();
            }
            // 读取边各个边
            for(int i = 0; i < e; i++) {
                int a = scanner.nextInt();
                int b = scanner.nextInt();
                int weight = scanner.nextInt();
                validateVertex(a);
                validateVertex(b);
                addEdge(a, b, weight);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("边数少于指定的值！");
        }
    }
    
    public CandyWeightedGraph(String filename) {
        this(filename, false);
    }
    
    public CandyWeightedGraph(int vertex_num, boolean directed) {
        this.vertex_num = vertex_num;
        this.directed = directed;
        this.edge_num = 0;
        this.adj = new TreeMap[vertex_num];
        for(int i = 0; i < vertex_num; i++) {
            this.adj[i] = new TreeMap<>();
        }
        
        this.edge_num++;
    }
    
    public void addEdge(int a, int b, int weight) {
        validateVertex(a);
        validateVertex(b);
        if(a == b) {
            throw new IllegalArgumentException("检测到了自环边！");
        }
        if(adj[a].containsKey(b)) {
            throw new IllegalArgumentException("检测到了平行边！");
        }
        
        adj[a].put(b, weight);
        if(!directed) {
            adj[b].put(a, weight);
        }
    }
    
    /**
     *  判断顶点是否合法
     * @param v
     */
    public void validateVertex(int v) {
        if(v < 0 || v >= vertex_num) {
            throw new IllegalArgumentException("顶点" + v + "不合法！");
        }
    }
    
    /**
     *  获取顶点数
     * @return
     */
    public int getVertex_num() {
        return vertex_num;
    }

    /**
     *  获取边数
     * @return
     */
    public int getEdge_num() {
        return edge_num;
    }
    
    /**
     * 判断顶点1和顶点2之间是否有一条边
     * @param v
     * @param w
     * @return
     */
    public boolean hasEdge(int v, int w) {
        validateVertex(v);
        validateVertex(w);
        return adj[v].containsKey(w);
    }
    
    /**
     * 删除顶点v和w之间的一条边
     * @param v
     * @param w
     */
    public void removeEdge(int v, int w) {
        validateVertex(v);
        validateVertex(w);
        adj[v].remove(w);
        if(!directed) {
            adj[w].remove(v);
        }
    }
    
    @Override
    public Object clone() {
        Object clonedGraph = null;
        try {
            // 将当前对象写入字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();
            // 分配内存，写入原始对象，生成新对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            clonedGraph = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return clonedGraph;
    }
    
    /**
     * 返回和某个顶点相邻的所有顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adjacentVertexes(int v) {
        validateVertex(v);
        return adj[v].keySet();
    }
    
    /**
     * 获取以v和w为顶点的边的权值
     * @param v
     * @param w
     * @return
     */
    public Integer getWeight(int v, int w) {
        if(!hasEdge(v, w)) {
            throw new IllegalArgumentException(String.format("顶点 %d 和顶点  %d 之间没有边", v, w));
        }
        return adj[v].get(w);
    }
    
    /**
     * 修改以v和w为顶点的边的权值
     * @param v
     * @param w
     * @param i
     */
    public void setWeight(int v, int w, int newWeight) {
        if(!hasEdge(v, w)) {
            throw new IllegalArgumentException(String.format("顶点 %d 和顶点  %d 之间没有边", v, w));
        }
        adj[v].put(w, newWeight);
        if(!directed) {
            adj[w].put(v, newWeight);
        }
    }

    /**
     * 返回一个顶点的度
     * @param v
     * @return
     */
    /*public int getDegree(int v) {
        validateVertex(v);
        return adj[v].size();
    }*/

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(String.format("顶点数  = %d\n边数 = %d\n", vertex_num, edge_num));
        sb.append("  ");
        for(int i = 0; i < vertex_num; i++) {
            sb.append(i + "\t");
        }
        sb.append('\n');
        for(int v = 0; v < vertex_num; v++) {
            // 打印行下标
            sb.append(v + " ");
            for(Entry<Integer, Integer> entry : adj[v].entrySet()) {
                sb.append(entry.getKey() + "[" + entry.getValue() + "]" + "\t");
            }
            sb.append('\n');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        //CandyWeightedGraph graph = new CandyWeightedGraph("testData/weightedGraph/graph.txt");
        CandyWeightedGraph graph = new CandyWeightedGraph("testData/weightedGraph/shortestPath/Floyed/graph3.txt");
        // 打印邻接矩阵，验证图是否被正确保存
        //adjacentMatrix.printAdj();
        System.out.println(graph);
        System.out.println("1的邻边有：" + graph.adjacentVertexes(1));
        System.out.println(graph.hasEdge(0, 1));
        // System.out.println(graph.hasEdge(0, 5));
        System.out.println("=============");
        CandyWeightedGraph graph2 = new CandyWeightedGraph("testData/weightedGraph/shortestPath/Floyed/graph3.txt", true);
        // 打印邻接矩阵，验证图是否被正确保存
        //adjacentMatrix.printAdj();
        System.out.println(graph2);
        System.out.println("1的邻边有：" + graph2.adjacentVertexes(1));
        System.out.println(graph2.hasEdge(0, 1));
        //System.out.println(graph2.hasEdge(0, 5));
    }
}
